package cn.hzc.fortess.system.controller;

import cn.hzc.fortess.core.common.ResponseData;
import cn.hzc.fortess.core.common.annotion.RequestPermission;
import cn.hzc.fortess.core.common.constant.Const;
import cn.hzc.fortess.core.common.BizErrorEnum;
import cn.hzc.fortess.core.common.exception.ServiceException;
import cn.hzc.fortess.system.entity.Dept;
import cn.hzc.fortess.system.node.ZTreeNode;
import cn.hzc.fortess.system.page.Pagination;
import cn.hzc.fortess.system.search.DeptSearch;
import cn.hzc.fortess.system.service.DeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.SwaggerDefinition;
import org.apache.shiro.authz.annotation.Logical;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.net.URLDecoder;
import java.util.List;
import java.util.Objects;

@Api(tags={"组织部门管理"})
@Controller
@RequestMapping("/sam/dept")
public class DeptController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(DeptController.class);

    @Autowired
    private DeptService deptService;

    @ApiIgnore
    @RequestMapping(value = "",method = RequestMethod.GET)
    public String index() {
        return buildToView("index.html");
    }

    @ApiIgnore
    @RequestMapping(value = "/add",method = RequestMethod.GET)
    public String addToView(@RequestParam(required = false) Integer pid) {
        Dept dept = new Dept();
        if (!Const.isTreeRoot(pid)) {
            Dept parentDept = deptService.getById(pid);
            dept.setParentId(parentDept.getId());
            dept.setParentName(parentDept.getDeptName());
        }
        setAttr("dept", dept);
        return buildToView("form.html");
    }

    @ApiOperation(value = "创建部门")
    @RequestMapping(value = "/add.json",method = RequestMethod.POST)
    @ResponseBody
    @RequestPermission("sam:dept:add")
    public ResponseData create(Dept dept) {
        if (Const.isTreeRoot(dept.getParentId())) {
            throw new ServiceException(BizErrorEnum.REQUEST_DEPT_PARENTID_ERROR);
        }
        Dept parentDept = deptService.getById(dept.getParentId());
        dept.setLesseeId(parentDept.getLesseeId());
        this.deptService.add(dept);
        return ResponseData.success();

    }

    @ApiIgnore
    @RequestMapping(value = "/edit/{id}",method = RequestMethod.GET)
    public String editToView(@PathVariable("id") Integer id) {
        Dept dept = deptService.getById(id);
        if(Const.isTreeRoot(dept.getParentId())) {
            dept.setParentName("-");
        }else{
            dept.setParentName(deptService.getById(dept.getParentId()).getDeptName());
        }
        setAttr("dept", dept);
        return buildToView("form.html");
    }

    @ApiOperation(value = "编辑部门")
    @RequestMapping(value = "/edit.json",method = RequestMethod.POST)
    @ResponseBody
    @RequestPermission("sam:dept:edit")
    public ResponseData edit(Dept dept) {
        if (Objects.equals(dept.getId(), dept.getParentId())) {
            throw new ServiceException(BizErrorEnum.REQUEST_DEPT_PARENTID_ERROR);
        }
        final Dept dept_= deptService.getById(dept.getId());
        if(Const.isTreeRoot(dept_.getParentId())
                && (!Objects.equals(dept.getParentId(),dept_.getParentId())) ){
            throw new ServiceException(BizErrorEnum.CANT_EDIT_ROOT_DEPT);
        }
        if((!Const.isTreeRoot(dept_.getParentId())) && Const.isTreeRoot(dept.getParentId())){
            throw new ServiceException(BizErrorEnum.CANT_EDIT_ROOT_DEPT);
        }
        deptService.update(dept);
        return ResponseData.success();
    }

    @ApiOperation(value = "删除部门")
    @RequestMapping(value = "/delete/{id}",method = RequestMethod.POST)
    @ResponseBody
    @RequestPermission("sam:dept:delete")
    public ResponseData delete(@PathVariable("id") Integer id) {
        Dept dept = deptService.getById(id);
        if (Const.isTreeRoot(dept.getParentId())) {
            throw new ServiceException(BizErrorEnum.REQUEST_NOT_ALLOW);
        }
        deptService.delete(id);
        return ResponseData.success();
    }

    @ApiOperation(value = "获取部门树状结构列表")
    @RequestMapping(value = "/tree",method = RequestMethod.POST)
    @ResponseBody
    @RequestPermission(value = {"sam:dept:list","sam:user:list"},logical = Logical.OR)
    public List<ZTreeNode> deptTree() {
        return  this.deptService.tree();
    }
    @ApiOperation(value = "获取部门分页列表")
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    @ResponseBody
    @RequestPermission("sam:dept:list")
    public Object page(DeptSearch search) {
        if(search.getDeptId()!=null){
            Dept dept =deptService.getById(search.getDeptId());
            search.setParentIds(dept.getParentIds()+"["+dept.getId()+"],");
        }
        return  this.deptService.getPage(search);

    }

    @ApiIgnore
    @RequestMapping(value = "/openDeptTreeSelect",method = RequestMethod.GET)
    @RequestPermission(value = {"sam:dept:list","sam:user:list"},logical = Logical.OR)
    public String deptTreeSelectList(@RequestParam("formName") String formName,
                               @RequestParam("formId") String formId,
                               @RequestParam("treeUrl") String treeUrl, Model model) throws Exception {

        model.addAttribute("formName", URLDecoder.decode(formName, "UTF-8"));
        model.addAttribute("formId", URLDecoder.decode(formId, "UTF-8"));
        model.addAttribute("treeUrl", URLDecoder.decode(treeUrl, "UTF-8"));

        return buildToView("dept_select.html");
    }

    @Override
    protected String moduleName() {
        return "dept";
    }
}
